using System;
using System.Collections.Generic;
using System.Text;

namespace NSimpleDB.Service.VistaDb.QueryProcessing.Compiler.AST
{
    // ItemSetFactor { "UNION" ItemSetFactor }
    internal class ItemSetTerm
    {
        private List<ItemSetFactor> itemSetFactorList;

        public ItemSetTerm(QueryTokenizer tok)
        {
            this.itemSetFactorList = new List<ItemSetFactor>();

            this.itemSetFactorList.Add(new ItemSetFactor(tok));
            while (tok.CurrentTokenType == QueryTokensTypes.IntersectionOp ||
                   tok.CurrentTokenType == QueryTokensTypes.AndOp)
            {
                tok.Read();
                this.itemSetFactorList.Add(new ItemSetFactor(tok));
            }
        }

        public ItemSetFactor[] ItemSetFactorList
        {
            get
            {
                return this.itemSetFactorList.ToArray();
            }
        }
    }


    // [ "NOT" ] "[" PredicateExpression "]"
    internal class ItemSetFactor
    {
        private bool negate = false;
        private PredicateExpression predicate;

        public ItemSetFactor(QueryTokenizer tok)
        {
            // not?
            if (tok.CurrentTokenType == QueryTokensTypes.NotOp)
            {
                this.negate = true;
                tok.Read();
            }

            // "[" PredicateExpression "]"
            if (tok.CurrentTokenType == QueryTokensTypes.OpenPredicate)
            {
                tok.Read();
                this.predicate = new PredicateExpression(tok);
                if (tok.CurrentTokenType == QueryTokensTypes.ClosePredicate)
                    tok.Read();
                else
                    throw new QueryCompilerException(QueryCompilerException.ErrorInvalidSymbol, "ItemSetFactor: Error in query! Expected ']', but found '{0}' [{1}] at position {2} in query.", tok.CurrentTokenText, tok.CurrentTokenType.ToString(), tok.CurrentTokenPosition);
            }
            else
                throw new QueryCompilerException(QueryCompilerException.ErrorInvalidSymbol, "ItemSetFactor: Error in query! Expected '[', but found '{0}' [{1}] at position {2} in query.", tok.CurrentTokenText, tok.CurrentTokenType.ToString(), tok.CurrentTokenPosition);
        }

        public bool Negate
        {
            get
            {
                return this.negate;
            }
        }

        public PredicateExpression Predicate
        {
            get
            {
                return this.predicate;
            }
        }
    }
}
